<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8" />
	<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
	<meta name="renderer" content="webkit" />
	<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
	<title>前端压缩图片示例</title>
	<style>
		body {
			font-size: 16px; 
			font-family: 'PingFang SC','Microsoft YaHei','Helvetica Neue','Helvetica','Arial',sans-serif;
		}
		.form-group {
			display: flex;
			margin-bottom: .5rem;
		}
		.file-upload {
			line-height: 1.25rem;
			background-color: #fff;
			border: 1px solid #d4d4d4;
			border-radius: .125rem;
		}
		.quote {
			text-align:center; 
			color: lightgray;
		}
	</style>
</head>
<body>
	<section>
		<form name="form1">
			<div class="form-group">
				<div><label>上传图片：</label></div>
				<div>
					<input type="file" name="file" id="fileUpImg" accept="image/*" class="file-upload"/>
				</div>
			</div>
			<div class="form-group">
				<div><label style="color: transparent">图片预览：</label></div>
				<div>
					<div class="preview"><img id="compressionPreview" alt="预览图" src="./assets/img/default.jpg" width="256" /></div>
					<div class="quote"><label id="compressionTips">请选择图片上传，稍后将进行压缩</label></div>
				</div>
			</div>
		</form>	
	</section>
	
	<!--Recommended Scripts Position-->
	<script type="module">
		import ImageCompressor from './utils/image-compressor.js';
		var imgCompressor = new ImageCompressor(),
			fileUpImg = document.getElementById("fileUpImg"),
			compressionPreview = document.getElementById("compressionPreview"),
			compressionTips = document.getElementById("compressionTips");
		
		//监听上传控件事件
		fileUpImg.onchange = function(){			
			compressionTips.textContent = "压缩处理中，请等待完成…";
			let _this = this, fileObj = _this.files[0];
			
			//压缩图片，这里优化目标大小设为 100KB （可能优化不成功）；如果优化目标大小设为0，表示只要压缩就行，不期望达到某一目标大小
			imgCompressor.compress({
				file: fileObj,
				optimizedSize: 100*1024,
				width: 480,
				quality: 0.95,
				done: function(res){
					console.log(res);
					//如果压缩成功
					if(res && res.code == 0){
						//TODO
						let data = res.data;
						if(data.dataURL) {
							compressionPreview.src = data.dataURL;
							compressionTips.textContent = "压缩成功！";
						}
						
						//新建一个 FormData 对象
						let formData = new FormData();
						formData.append("file", data.file); //加入文件对象
						
						//可使用 Ajax 将 FormData 上传到服务端
						//$.ajax({
						//	url: "xxx",
						//	type: "POST",
						//	data: formData,
						//	sunccess: function(res){}
						//});
					} else {
						compressionTips.textContent = "压缩失败，未达到优化目标";
						console.log("Compress Failed. Image Too Large");
					}
				}
			});
		};
		
	</script>
</body>
</html>